package com.ckv.qcm.model.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import com.ckv.qcm.model.Theme;

public class ThemeDAO extends DAO {

	public Theme find(long id) {
		Theme theme = null;
		try {
			ResultSet result = this.connection.createStatement().executeQuery(
					"SELECT * FROM Themes WHERE idTheme = " + id);
			if (result.next())
				theme = new Theme(id, result.getString("nomTheme"));
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return theme;
	}

	public ArrayList<Theme> findAll() {
		ArrayList<Theme> themes = new ArrayList<Theme>();
		try {
			ResultSet result = this.connection.createStatement().executeQuery(
					"SELECT * FROM Themes");
			while (result.next()) {
				themes.add(new Theme(result.getLong("idTheme"), result
						.getString("nomTheme")));
			}
			return themes;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Theme create(Theme theme) {
		PreparedStatement preparedStatement = null;
		ResultSet generatedKeys = null;
		try {
			preparedStatement = this.connection.prepareStatement(
					"INSERT INTO Themes (nomTheme) VALUES (?)",
					Statement.RETURN_GENERATED_KEYS);
			preparedStatement.setString(1, theme.getName());

			int affectedRows = preparedStatement.executeUpdate();
			if (affectedRows == 0) {
				throw new SQLException(
						"Creating user failed, no rows affected.");
			}

			generatedKeys = preparedStatement.getGeneratedKeys();
			if (generatedKeys.next()) {
				theme = this.find(generatedKeys.getLong(1));
			} else {
				throw new SQLException(
						"Creating user failed, no generated key obtained.");
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return theme;
	}

	public Theme update(Theme theme) {
		try {
			this.connection.createStatement().executeUpdate(
					"UPDATE Themes SET nomTheme = '" + theme.getName()
							+ "' WHERE idTheme = " + theme.getId());
			theme = this.find(theme.getId());
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return theme;
	}

	public boolean delete(Theme theme) {
		try {
			this.connection.createStatement().executeUpdate(
					"DELETE FROM Themes WHERE idTheme = " + theme.getId());
			return true;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return false;
	}

}
